package com.zuorenke.help;

import com.zuorenke.vertx.anno.Order;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Z.R.K
 * @description
 * @create 2019-05-10 09:47:15
 **/
public class SortUtils {
	private SortUtils() {
	}
	
	public static <T> List<Class<? extends T>> sortOrder(Collection<Class<? extends T>> handlers, boolean desc) {
		Comparator<Class<?>> comparator = (c1, c2) -> {
			Order order1 = c1.getAnnotation(Order.class);
			Order order2 = c2.getAnnotation(Order.class);
			if (desc) {
				if (order2 == null) {
					if (order1 == null) {
						return 0;
					} else {
						return -1;
					}
				}
				if (order1 == null) {
					return 1;
				}
				return Integer.compare(order2.value(), order1.value());
			} else {
				if (order1 == null) {
					if (order2 == null) {
						return 0;
					} else {
						return -1;
					}
				}
				if (order2 == null) {
					return 1;
				}
				return Integer.compare(order1.value(), order2.value());
			}
		};
		return handlers.stream().sorted(comparator).collect(Collectors.toList());
	}
	
}
